<template>
    <!-- 预订页面 -->
    <div class="reserve-wrapper">
        <reserve-header></reserve-header>
        <form @submit.prevent="doReserve(orderParams)">
            <img :src="roomDetail.image">
            <div class="reserve-title">
                <p>{{roomDetail.type}}</p>
                <span>请选择房间号：</span>
            </div>
            <div class="room-environment">
                <!-- 使用路由控制页面的转换 -->
                <div class="room-list">
                    <room-item v-for="item in rooms" :key="item.rid" :room="item" @click="setRid(item.rid)">
                        <input type="text" v-model="orderParams.rid" hidden>
                    </room-item>
                </div>
                <router-view></router-view>
            </div>
            <calendar :params="orderParams" @getTime="getTime"></calendar>
            <div class="order-commit">
                <div class="commit-msg">
                    <div class="price">
                        应付总额<span>￥{{orderParams.amount}}</span>
                    </div>
                    <div class="deposit">
                        定金<span>￥{{roomDetail.deposit}}</span>
                    </div>
                    <span>在{{orderParams.checkin_time!=''?orderParams.checkin_time:new Date().getFullYear()+'/'+new Date().getMonth()+'/'+new Date().getDate()}}
                        12:00之前可免费退房，超时退房不返还定金！</span>
                </div>
                <input type="submit" value="预订">
            </div>
        </form>
        <app-dialog :show="DialogBox.show" :type="DialogBox.type">{{DialogBox.msg}}</app-dialog>
        <loading :show="isLoading">正在提交...</loading>
    </div>
</template>

<script>
    /**
     * 页面操作流程：
     *  用户可以查看房间的数据，并以此为参照来选择房间号
     *  用户需要通过日期选择器选择入住日期及退房日期
     *  房间号、入住时间及退房时间均为必选项
     *  选择完毕后点击预订按钮，发送预订请求
     */

    import {
        reactive,
        onBeforeMount,
        ref
    } from 'vue'

    import {
        useStore
    } from 'vuex'

    import {
        useRoute,
        useRouter
    } from 'vue-router'

    import {
        getTypeData,
        reserve
    } from '../services'

    import {
        DialogBox
    } from '../utils'

    import LoginHeader from '../components/user/LoginHeader'
    import RoomItem from '../components/reserve/RoomItem'
    import Calendar from '../components/reserve/Calendar'

    export default {
        name: 'Reserve',
        emits: ['getTime'],
        props: {
            tid: [String, Number]
        },
        components: {
            'ReserveHeader': LoginHeader,
            RoomItem,
            Calendar
        },
        setup(props) {
            const route = useRoute()
            const store = useStore()
            const router = useRouter()
            let user = store.state.user

            let rooms = reactive(new Array())

            let roomDetail = reactive({
                deposit: 0,
                price: 0,
                image: '',
                type: ''
            })
            let isLoading = ref(false)

            let orderParams = reactive({
                rid: parseInt(route.params.rid) || 0,
                days: 0,
                checkinTime: '',
                leaveTime: '',
                amount: 0,
                deposit: 0
            })

            function setRid(rid) {
                orderParams.rid = rid
            }

            onBeforeMount(() => {
                // 在渲染前发送请求并保存数据
                getTypeData(props.tid).then((response) => {
                    if (response.data.code == 200) {
                        rooms.splice(0, rooms.length)
                        rooms.push(...response.data.object)
                        roomDetail.deposit = response.data.deposit
                        roomDetail.price = response.data.price
                        roomDetail.image = response.data.image
                        roomDetail.type = response.data.type
                        orderParams.deposit = roomDetail.deposit
                    }
                })
            })

            const getTime = (newValue) => {
                orderParams.days = newValue.days
                orderParams.checkinTime = newValue.checkin_time
                orderParams.leaveTime = newValue.checkout_time
                orderParams.amount = orderParams.days == 0 ? roomDetail.price : roomDetail.price * orderParams.days
            }

            function doReserve(orderParams) {
                // 先检测用户参数的选择是否符合要求，符合后发送请求
                if (orderParams.rid == 0) {
                    DialogBox.showDialog('请先选择房间号')
                } else if (orderParams.checkinTime.length == 0 || orderParams.checkinTime == '') {
                    DialogBox.showDialog('请先选择入住日期')
                } else if (orderParams.leaveTime.length == 0 || orderParams.leaveTime == '') {
                    DialogBox.showDialog('请先选择退房日期')
                } else {
                    isLoading.value = true
                    // 发送post请求进行预订
                    reserve(orderParams, user.object.uid).then((response) => {
                        if (response.data.code == 200) {
                            isLoading.value = false
                            DialogBox.showDialog(response.data.msg + '，三秒后跳转', 'success')
                            setTimeout(() => {
                                router.push('/home')
                            }, 3000)
                        } else DialogBox.showDialog(response.data.msg)
                    }).catch((error) => {
                        DialogBox.showDialog('服务器繁忙，请稍后再试')
                    })
                }
            }

            return {
                rooms, // 存放当前房型对应的所有房间号
                orderParams, // 订单参数
                setRid, // 设置房间号
                doReserve, // 预订处理函数
                roomDetail, // 响应式对象，存放选中房间的信息
                getTime, // 获取并设置订单参数
                DialogBox,
                isLoading
            }
        }
    }
</script>

<style lang="scss" scoped>
    @import '../style/reserve.scss';
</style>